import { request } from "../../utils/http"

const convertData = data => {
  return Object.keys(data.achievement).sort((a, b) => {
    return a > b ? -1 : a < b ? 1 : 0
  }).map(k => {
    return { title: k, children: data.achievement[k] }
  })
}

Page({
  data: {
    currentTab: 0,
    tabs: ['测验', '练习'],
    exampleData: [],
    examinationData: [],
    expands: []
  },

  onSwitchNav(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.current
    })
  },

  onSwiperChange(e) {
    this.setData({
      currentTab: e.detail.current
    })
  },

  onToggleExpand(e) {
    const { index } = e.currentTarget.dataset
    const arrName = +this.data.currentTab === 1 ? 'exampleData' : 'examinationData'
    const item = this.data[arrName][index]
    const expandItemIndex = this.data.expands.indexOf(item.title)
    if (expandItemIndex > -1) {
      this.data.expands.splice(expandItemIndex, 1)
      this.setData({
        expands: this.data.expands
      })
    } else {
      this.setData({
        expands: [...this.data.expands, item.title]
      })
    }
  },

  onShow: function () {
    request('/api/portal/exam/achievement/history').then(data => {
      this.setData({
        examinationData: convertData(data)
      })
    })
    request('/api/portal/exam/achievementQuestion/history').then(data => {
      this.setData({
        exampleData: convertData(data)
      })
    })
  }
})
